import * as assert from 'assert';
import * as fs from 'fs';
import 'mocha';
import { join, normalize } from 'path';
import { commands, DebugConsoleMode, Uri } from 'vscode';

function assertUnchangedTokens(snippetsPath: string, resultsPath: string, snippet: string, done: any) {
	const testFixurePath = join(snippetsPath, snippet);
	
	return commands.executeCommand('_workbench.captureSyntaxTokens', Uri.file(testFixurePath)).then(data => {
		try {
			const resultPath = join(resultsPath, snippet.replace('.', '_') + '.json');
			const previousData = JSON.parse(fs.readFileSync(resultPath).toString());

			compareSyntaxArray(data, previousData);
			done();
		}
		catch (error) {
			done(error);
		}
	}, done);
}

function compareSyntaxArray(data: any, previousData: any): void {
	let dataIdx: number = 0;
	let prevDataIdx: number = 0;

	while (dataIdx < data.length && prevDataIdx < previousData.length) {
		// skipping objects in data that are not in the generated json
		while (previousData[prevDataIdx].c !== data[dataIdx].c && dataIdx + 1 < data.length) {
 			++dataIdx;
 		}
		assert.strictEqual(previousData[prevDataIdx].c, data[dataIdx].c);
		assert.strictEqual(previousData[prevDataIdx].t, data[dataIdx].t);

		++dataIdx;
		++prevDataIdx;
	}

	assert(prevDataIdx === previousData.length);
}

suite('Integration test for highlighting the ETS language', () => {
	const testPath = normalize(join(__dirname, '../../test/'));
	const snippetsPath = join(testPath, 'snippets');
	const resultsPath = join(testPath, 'results');

	for (const snippet of fs.readdirSync(snippetsPath)) {
		test(`colorize: ${snippet}`, function (done) {
			commands.executeCommand('workbench.action.closeAllEditors').then(() => {
				assertUnchangedTokens(snippetsPath, resultsPath, snippet, done);
			});
		});
	}
});

